//
//  YLTransactionInfo.swift
//  YLPaymentKit
//
//  Created by changhe on 2025/4/12.
//

import Foundation
import StoreKit

/// 交易状态
public enum YLTransactionState {
    case purchasing    // 正在购买
    case purchased     // 已购买
    case failed        // 失败
    case restored      // 已恢复
    case deferred      // 延迟
    case unknown       // 未知状态
}

/// 交易信息模型
public struct YLTransactionInfo {
    /// 交易ID
    public var transactionId: String = ""
    
    /// 商品ID
    public var productId: String = ""
    
    /// 交易日期
    public var transactionDate: Date = Date()
    
    /// 原始交易ID（订阅更新时有值）
    public var originalTransactionId: String? = nil
    
    /// 交易状态
    public var state: YLTransactionState = .unknown
    
    /// 错误信息
    public var error: Error? = nil
    
    /// 原始交易对象
    public var rawTransaction: Any
    
    /// API版本 (1=StoreKit 1, 2=StoreKit 2)
    public var apiVersion: Int = 0
    
    /// 订单ID
    public var orderId: String? = nil
    
//    /// 初始化
//    public init() {
//        // 默认初始化
//        rawTransaction = []
//    }
    
    /// 从StoreKit 1的交易初始化
    public init(skTransaction: SKPaymentTransaction) {
        self.transactionId = skTransaction.transactionIdentifier ?? ""
        self.productId = skTransaction.payment.productIdentifier
        self.transactionDate = skTransaction.transactionDate ?? Date()
        self.originalTransactionId = skTransaction.original?.transactionIdentifier
        self.rawTransaction = skTransaction
        self.apiVersion = 1
        
        // 映射交易状态
        switch skTransaction.transactionState {
        case .purchased: self.state = .purchased
        case .failed: self.state = .failed
        case .restored: self.state = .restored
        case .purchasing: self.state = .purchasing
        case .deferred: self.state = .deferred
        @unknown default: self.state = .unknown
        }
        
        self.error = skTransaction.error
        
        // 尝试从payment.applicationUsername中获取订单ID
        if let applicationUsername = skTransaction.payment.applicationUsername {
            self.orderId = YLOrderUUIDTransformer.fromUUID(applicationUsername)
        }
    }
    
    /// 从StoreKit 2的交易初始化
    @available(iOS 15.0, *)
    public init(storeKitTransaction: StoreKit.Transaction) {
        self.transactionId = storeKitTransaction.id.description
        self.productId = storeKitTransaction.productID
        self.transactionDate = storeKitTransaction.purchaseDate
        self.originalTransactionId = storeKitTransaction.originalID.description
        self.rawTransaction = storeKitTransaction
        self.apiVersion = 2
        self.state = .purchased
        
        // 尝试获取订单ID的优先级：
        // 1. 从appAccountToken获取
        if let appAccountToken = storeKitTransaction.appAccountToken {
            self.orderId = YLOrderUUIDTransformer.fromUUID(appAccountToken.uuidString)
        }
    }
}
